<!-- src/views/video/avatar/index.vue -->
<template>
  <div class="avatar-container">
    <!-- 添加工具栏 -->
    <el-card class="mb-4">
      <el-button type="primary" @click="handleSync">
        <el-icon><Refresh /></el-icon>手动同步
      </el-button>
      <el-button @click="showExcludeDialog">
        <el-icon><Setting /></el-icon>排除设置
      </el-button>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="mb-4">
      <el-col :span="6" v-for="(count, type) in avatarStats" :key="type">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-content">
            <div class="stats-title">{{ getStatsTitle(type) }}</div>
            <div class="stats-number">{{ count }}</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索和过滤 -->
    <el-card class="mb-4">
      <el-form :model="queryParams" :inline="true">
        <el-form-item label="性别" style="width: 180px">
          <el-select v-model="queryParams.gender" placeholder="选择性别" clearable>
            <el-option label="男性" value="male" />
            <el-option label="女性" value="female" />
          </el-select>
        </el-form-item>
        <el-form-item label="类型" style="width: 180px">
          <el-select v-model="queryParams.premium" placeholder="选择类型" clearable>
            <el-option label="基础版" :value="false" />
            <el-option label="高级版" :value="true" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>查询
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 虚拟人物列表 -->
    <el-card v-loading="loading">
      <el-row :gutter="20">
        <el-col
            :span="6"
            v-for="avatar in avatars"
            :key="avatar.avatarId"
            class="mb-4"
        >
          <el-card
              :body-style="{ padding: '0px' }"
              shadow="hover"
              class="avatar-card"
          >
            <div class="avatar-image">
              <el-image
                  :src="avatar.previewImageUrl"
                  fit="cover"
                  loading="lazy"
              >
                <template #error>
                  <div class="image-error">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
              <div class="avatar-tags">
                <el-tag size="small" :type="getGenderType(avatar.gender)">
                  {{ getGenderLabel(avatar.gender) }}
                </el-tag>
                <el-tag size="small" type="warning" v-if="avatar.premium">
                  高级版
                </el-tag>
                <el-tag size="small" type="warning" v-if="avatar.basic">
                  基础版
                </el-tag>
              </div>
            </div>
            <div class="avatar-info">
              <h3 class="avatar-name">{{ avatar.avatarName }}</h3>
              <div class="avatar-actions">
                <el-button
                    type="primary"
                    link
                    @click="handlePreview(avatar)"
                >
                  预览视频
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :total="avatarStore.total"
            :page-sizes="[12, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 排除名单设置弹窗 -->
    <el-dialog
        v-model="excludeDialog.visible"
        title="排除名单管理"
        width="800px"
    >
      <!-- 搜索区域 -->
      <el-form :inline="true" :model="avatarStore.excludeQuery">
        <el-form-item label="角色名称">
          <el-input
              v-model="avatarStore.excludeQuery.avatarName"
              placeholder="请输入角色名称"
              clearable
              style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleExcludeSearch">查询</el-button>
          <el-button @click="handleExcludeReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 工具栏 -->
      <div class="toolbar">
        <el-button type="primary" @click="handleAddExclude">
          <el-icon><Plus /></el-icon>添加
        </el-button>
        <el-button
            type="danger"
            :disabled="!selectedExcludes.length"
            @click="handleBatchDelete"
        >
          <el-icon><Delete /></el-icon>批量删除
        </el-button>
      </div>

      <!-- 表格 -->
      <el-table
          :data="avatarStore.excludeList"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="avatarName" label="角色名称" />
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button
                type="danger"
                link
                @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
            v-model:current-page="avatarStore.excludeQuery.pageNum"
            v-model:page-size="avatarStore.excludeQuery.pageSize"
            :total="avatarStore.totalExclude"
            :page-sizes="[12, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChangeExclude"
            @current-change="handleCurrentChangeExclude"
        />
      </div>
    </el-dialog>

    <!-- 预览弹窗 -->
    <el-dialog
        v-model="previewDialog.visible"
        title="虚拟人物预览"
        width="800px"
        :close-on-click-modal="false"
    >
      <video
          v-if="previewDialog.videoUrl"
          :src="previewDialog.videoUrl"
          controls
          class="preview-video"
      ></video>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import {Search, Refresh, Picture, Setting, Plus, Delete} from '@element-plus/icons-vue'
import { useAvatarStore } from '@/stores/video/avatar'
import {ElMessage, ElMessageBox} from 'element-plus'
import { storeToRefs } from 'pinia'
import {getGenderLabel, getGenderType} from "@/utils/label.js";

const selectedExcludes = ref([])
const avatarStore = useAvatarStore()
const { avatars, avatarStats, loading } = storeToRefs(avatarStore)

// 查询参数
const queryParams = reactive({
  gender: '',
  premium: null,
  pageSize: 12,
  pageNum: 1,
})

// 预览弹窗
const previewDialog = reactive({
  visible: false,
  videoUrl: ''
})

// 获取统计标题
const getStatsTitle = (type) => {
  const titles = {
    'male': '男性人物',
    'female': '女性人物',
    'premium': '高级版本',
    'basic': '基础版本',
    'total': '总数量'
  }
  return titles[type] || type
}

// 查询
const handleExcludeSearch = () => {
  avatarStore.excludeQuery.pageNum = 1
  avatarStore.fetchExcludeList()
}

// 重置
const handleExcludeReset = () => {
  avatarStore.excludeQuery.avatarName = ''
  handleExcludeSearch()
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedExcludes.value = selection
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm('确认删除选中的记录吗？', '提示', {
      type: 'warning'
    })
    const ids = selectedExcludes.value.map(item => item.id)
    await avatarStore.batchDeleteExcludeName(ids)
  } catch {
    // 用户取消删除
  }
}

// 单个删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确认删除该记录吗？', '提示', {
      type: 'warning'
    })
    await avatarStore.removeExcludeName([row.id])
  } catch {
    // 用户取消删除
  }
}

// 分页方法
const handleSizeChangeExclude = (val) => {
  queryParams.pageSize = val
  handleExcludeSearch()
}

const handleCurrentChangeExclude = (val) => {
  queryParams.pageNum = val
  handleExcludeSearch()
}

// 查询
const handleQuery = () => {
  avatarStore.fetchAvatars(queryParams)
}

// 重置
const resetQuery = () => {
  queryParams.gender = ''
  queryParams.premium = null
  handleQuery()
}

// 分页方法
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  handleQuery()
}

const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  handleQuery()
}

// 预览
const handlePreview = (avatar) => {
  if (!avatar.previewVideoUrl) {
    ElMessage.warning('暂无预览视频')
    return
  }
  previewDialog.videoUrl = avatar.previewVideoUrl
  previewDialog.visible = true
}

const excludeDialog = reactive({
  visible: false
})
const excludeList = ref([])

const handleSync = async () => {
  try {
    await avatarStore.manualSync()
    ElMessage.success('同步成功')
  } catch (error) {
    ElMessage.error(error.message || '同步失败')
  }
}

const showExcludeDialog = async () => {
  excludeDialog.visible = true
  await fetchExcludeList()
}

const fetchExcludeList = async () => {
  await avatarStore.fetchExcludeList()
  excludeList.value = avatarStore.excludeList
}

const handleAddExclude = () => {
  ElMessageBox.prompt('请输入需要排除的角色名称', '添加排除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(({ value }) => {
    const data = {
      avatarName: value
    }
    avatarStore.addExcludeName(data)
    fetchExcludeList()
  })
}

const handleRemoveExclude = async (row) => {
  try {
    await avatarStore.removeExcludeName(row.id)
    await fetchExcludeList()
    ElMessage.success('删除成功')
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 初始化
onMounted(() => {
  handleQuery()
  avatarStore.fetchStats()
})
</script>

<style scoped>
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.avatar-container {
  padding: 20px;
}

.mb-4 {
  margin-bottom: 16px;
}

.stats-card {
  height: 100px;
}

.stats-content {
  text-align: center;
}

.stats-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.stats-number {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}

.avatar-card {
  transition: all 0.3s;
}

.avatar-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.avatar-image {
  position: relative;
  height: 200px;
  text-align: center;
}

.avatar-image .el-image {
  width: 50%;
  height: 100%;
}

.image-error {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f5f7fa;
  color: #909399;
}

.avatar-tags {
  position: absolute;
  top: 10px;
  right: 10px;
  display: flex;
  gap: 5px;
}

.avatar-info {
  padding: 14px;
}

.avatar-name {
  margin: 0 0 10px 0;
  font-size: 16px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.avatar-actions {
  display: flex;
  justify-content: space-between;
}

.preview-video {
  width: 100%;
  max-height: 450px;
}
</style>